# routers/admin.py
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from database import get_db
from models import User, Course
from schemas import UserCreate, UserOut, CourseCreate, CourseOut
from routers.users import get_current_user
from passlib.context import CryptContext
from typing import List

router = APIRouter()
pwd_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

# 查询所有教师及其课程
@router.get("/teachers", tags=["管理员模块"])
def list_teachers(db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
    if current_user.role != "admin":
        raise HTTPException(status_code=403, detail="没有权限")

    teachers = db.query(User).filter(User.role == "teacher").all()

    result = []
    for teacher in teachers:
        courses = db.query(Course).filter(Course.teacher_id == teacher.id).all()
        result.append({
            "id": teacher.id,
            "username": teacher.username,
            "courses": [{"id": c.id, "name": c.name} for c in courses]
        })

    return result

# 添加教师账号
@router.post("/teachers", response_model=UserOut, tags=["管理员模块"])
def create_teacher(user: UserCreate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
    if current_user.role != "admin":
        raise HTTPException(status_code=403, detail="没有权限")
    hashed_pw = pwd_context.hash(user.password)
    db_user = User(username=user.username, password=hashed_pw, role="teacher")
    db.add(db_user)
    db.commit()
    db.refresh(db_user)
    return db_user

# 为教师分配课程
@router.post("/courses", response_model=CourseCreate, tags=["管理员模块"])
def assign_course(course: CourseCreate, db: Session = Depends(get_db), current_user: User = Depends(get_current_user)):
    if current_user.role != "admin":
        raise HTTPException(status_code=403, detail="没有权限")
    teacher = db.query(User).filter(User.id == course.teacher_id, User.role == "teacher").first()
    if not teacher:
        raise HTTPException(status_code=404, detail="教师不存在")
    db_course = Course(name=course.name, teacher_id=teacher.id)
    db.add(db_course)
    db.commit()
    db.refresh(db_course)
    return db_course
